package com.cheyun.netsalev3.viewmodel

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
//import android.icu.text.SimpleDateFormat
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.bean.NameIdParam
import com.cheyun.netsalev3.bean.dm.DmClueList
import com.cheyun.netsalev3.bean.dm.DmDealUser
import com.cheyun.netsalev3.bean.dm.DmHistory
import com.cheyun.netsalev3.bean.records.RecordsParam
import com.cheyun.netsalev3.repository.DmClueDetailsRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.dm.detail.DmCallRecordActivity
import com.cheyun.netsalev3.view.dm.detail.DmClueFollowActivity
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.MyDialog
import com.jeremyliao.liveeventbus.LiveEventBus
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author Michael
 * @date  2018/12/12 - 14:34.
 */
class DmClueDetailsActivityViewModel(var clueDetailsRepository: DmClueDetailsRepository) : BaseViewModel() {
    var dmClueList = ObservableField<DmClueList>()
    var lastHistory = ObservableField<DmHistory>()
    var recordsParam = RecordsParam()
    //历史纪录
    var recordsList = MutableLiveData<List<DmHistory>>()
    //底部按钮
    var bottomList = MutableLiveData<List<NameIdParam>>()

    var time = MutableLiveData<String>()
    var specName = MutableLiveData<String>()

    //移交用户
    var member:MutableList<DmDealUser> = mutableListOf();
    var memberName = ObservableField<String>("")
    var memberPosition = -1

    init {
        clueDetailsRepository.getDetail(this::setData)
    }

    @SuppressLint("NewApi")
    private fun setData(item: DmClueList, history:DmHistory?) {
        dmClueList.set(item)
        lastHistory.set(history)
        clueDetailsRepository.getRecords(this::setRecords)

        val format = SimpleDateFormat("yyyy-MM-dd HH:mm")
        var t = ""
        if(item.create_time.length == 13){
            t = format.format(Date(item.create_time.toLong()))
        }else{
            t = format.format(Date(item.create_time.toLong()*1000))
        }
        time.postValue(t)

        specName.postValue(item.brand_name +" " + item.series_name +" "+item.spec_name)

//        跟进：archive.purge 1
//        订车：archive.order 5
//        提车：archive.thenend 10
//        战败：archivecheck.fail 32
//       "archivepot.index", "archivepot.discard", "archivepot.failure", "archivepot.invalid"
        var userId = MySharedPreferences.getDmLoginData()?.user?.user_id;

        var temlist = ArrayList<NameIdParam>()
        if(item.user_id == 0){
            temlist.add(NameIdParam("移交", "0", R.drawable.a02_2_xsxq_handover))
        }else{
            if(item.user_id == userId){
                if(item.status == 2 || item.status == 3){
                    temlist.add(NameIdParam("跟进", "0", R.drawable.a01_1_1_zbxq_followup))
//            temlist.add(NameIdParam("战败", 0, R.drawable.a01_1_1_zbxq_falsedefeat))
//            temlist.add(NameIdParam("成交", 0, R.drawable.a01_1_1_zbxq_comfiredefeat1))
                    temlist.add(NameIdParam("移交", "0", R.drawable.a02_2_xsxq_handover))
                }else{
                    temlist.add(NameIdParam("跟进", "0", R.drawable.a01_1_1_zbxq_followup))
                    temlist.add(NameIdParam("移交", "0", R.drawable.a02_2_xsxq_handover))
                }
            }
        }
        bottomList.postValue(temlist)
    }

    fun refreshDetail(){
        clueDetailsRepository.getDetail(this::setData)
    }

    /**
     * 线索记录回调
     */
    fun setRecords(list: List<DmHistory>) {
        recordsList.postValue(list)
    }

    /**
     * 点击底部按钮
     */
    fun onClickBottom(view: View, item: NameIdParam) {
        bottomItem = item
        when (item.name) {
            "跟进" -> clueFollow(view, "1")
            "战败" -> clueFollow(view, "5")
            "成交" -> clueFollow(view, "4")
            "移交" -> clueTransfer(view)
        }
    }

    //底部按钮
    var bottomItem = NameIdParam("", "-1")
    var context: AppCompatActivity? = null

    init {
    }

    fun clueFollow(view: View,type:String){
        var intent = Intent(view.context, DmClueFollowActivity::class.java)
        intent.putExtra("clueId", dmClueList.get()?.id.toString())
        intent.putExtra("type", type)
        intent.putExtra("status", dmClueList.get()?.status.toString())
        intent.putExtra("isarrive", dmClueList.get()?.is_arrive.toString())

        view.context.startActivity(intent)
    }

    fun clueTransfer(view: View){
        getDealUser(view);

//        var intent = Intent(view.context, DmClueTransferActivity::class.java)
//        intent.putExtra("clueId", dmClueList.get()?.id.toString())
//        view.context.startActivity(intent)
    }

    fun getDealUser(view: View){
        var method: (List<DmDealUser>) -> Unit = {
            member.addAll(it)

            var content = view.context
            if (content is AppCompatActivity) {
                member?.apply {
                    var list = java.util.ArrayList<DialogParam>()
                    for (it in this) {
                        var item = DialogParam(it.name, it.userId.toString())
                        list.add(item)
                    }
                    var diolog = MyDialog.newInstance("移交线索", list)
                    diolog.huidiaPosition = this@DmClueDetailsActivityViewModel::myPopSetData
                    diolog.show(content.supportFragmentManager, "missiles2")
                }
            }
        }
        clueDetailsRepository.getDealusers(method);
    }

    /**
     * 选中移交回调
     */
    fun myPopSetData(position: Int) {
        memberPosition = position
        if (memberPosition != -1) {
            memberName.set(member!![memberPosition].name)
        }
        clickTransfer();
    }
    /**
     * 完成
     */
    fun clickTransfer() {
        if (memberPosition == -1) {
            return
        }

        var toUserId = ""
        var toUser = ""
        toUserId = member?.get(memberPosition)?.userId.toString()
        toUser = member?.get(memberPosition)?.name

        var method: () -> Unit = {
            transferSuccess()
        }

        clueDetailsRepository.clueTransfer(toUserId,toUser,"", method)
    }

    /**
     * 成功回调
     */
    fun transferSuccess() {
        LiveEventBus.get().with("dmclueupdatge").postValue("")
//        LiveEventBus.get().with("dmclueupdatge").postValue("")
        MyToast("移交成功")
    }

    /**
     *点击通话记录
     */
    fun callPhone(view: View, item: DmHistory) {
        var intent = Intent(view.context, DmCallRecordActivity::class.java)
        intent.putExtra("id", item.id)
        view.context.startActivity(intent)

//        if (item.mp3_url.isNullOrBlank()) {
//            Toast.makeText(view.context, "无法播放", Toast.LENGTH_LONG).show()
//            return
//        }
//
//        var context = view.context
//        if (context is AppCompatActivity) {
//            var pop = CallPopFragment.newInstance(item.mp3_url, "00:00", secondToMin(item.mp3_len))
//            pop.show(context.supportFragmentManager, "")
//        }
    }
    var context1: Context? = null
    var phone:String = ""
    fun onCall(view:View){
        var moth: (tel:String) -> Unit = {
            if(it.isEmpty()){
                Toast.makeText(view.context, "未绑定工作号", Toast.LENGTH_LONG).show()
            }else {
                var context = view.context
                if (context is AppCompatActivity) {
                    (context as AppCompatActivity).apply {
                        var dialog = MyContentDialog.newInstance("提示", "是否拨打电话")
                        dialog.onClickOk = this@DmClueDetailsActivityViewModel::onClickOk
                        dialog.show(this.supportFragmentManager, "")
                        context1 = view.context
                        phone = it;
                    }
                }
//                var dialog = MyContentDialog.newInstance("提示", "是否拨打电话？")
//                dialog.onClickOk = this@DmClueDetailsActivityViewModel::onClickOk
//                dialog.show()
//                context1 = view.context
//                phone = it;
//                FunctionUtils.callPhone(view.context, it)
            }
        }
        clueDetailsRepository.callPhone(dmClueList.get()?.id!!,moth);
    }

    /**
     * 点击弹窗ok
     */
    fun onClickOk() {
        FunctionUtils.callPhone(context1!!,phone)
    }

    fun getStatusText(status:Int):String{
        if(status == 5){
            return "战败"
        }else if(status == 4){
            return "成交"
        }else if(status == 3){
            return "通话"
        }else if(status == 2){
            return "移交"
        }else if(status == 1){
            return "跟进";
        }
        return "跟进"
    }

    fun secondToMin(v:Int):String{
        var min = v/60
        var s = v%60;
        if(min == 0)return s.toString() +" 秒     ";
        else{
            if(s == 0) return min.toString()+" 分     ";
            return min.toString()+" 分"+s.toString()+" 秒     "
        }
    }
}